<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:200px">
        <div>订单号</div>
        <el-input v-model.trim="param.orderNo" placeholder="请输入" clearable> </el-input>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>结算流向</div>
        <el-select v-model="param.invoiceDirection" clearable style="width:100%" placeholder="请选择" >
          <el-option v-for="item in DATA_invoiceDirections" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>结算单位</div>
        <el-input v-model.trim="param.businessName" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>发票号</div>
        <!-- <el-select v-model="param.boxType" style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.boxTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
        <el-input v-model.trim="param.invoiceNo" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>发票状态</div>
        <el-select v-model="param.invoiceStatus" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in DATA_invoiceStatuss" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>纳税人识别号</div>
        <el-input v-model.trim="param.creditCode" clearable placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>申请日期</div>
        <el-date-picker v-model="param.createDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:200px">
        <div>结算状态</div>
        <el-select v-model="param.closeStatus" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="(item,index) in param.closeStatuss" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:200px">
        <div>发票类型</div>
        <el-select v-model="param.invoiceType" clearable style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.invoiceTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>

    <div>
      <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
      <span style="margin-top: -40px;float: right;">
        <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
          <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
          </template>
          <template v-else>
              <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
          </template>
        </el-tooltip>
        <el-button type="primary" size="small" style="width:80px" round @click="applyRedInvoice">申请红冲</el-button>
        <el-button type="primary" size="small" style="width:80px" :disabled="!selection.length" round @click="" plain>导出</el-button>
      </span>
      <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @activInfo="activInfo" @activPay="activPay"
        @showInvoice="showInvoice" @applyInvoice="applyInvoice" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
      </Table>
    </div>


    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible">
      <div v-if="param.oprType == 'img'" style="text-align: center;">
        <pdfViewer v-for="(item,index) in param.pdfUrl" :key="index" :url="item.url"></pdfViewer>
      </div>
      <div v-if="param.oprType == 'rentFee'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>租箱费
        </div>
        <b>租箱费总计</b>
        <el-table :data="param.rentFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应收箱量"> </el-table-column>
          <el-table-column prop="dealAmount" label="应收租箱费总计"> </el-table-column>
          <el-table-column prop="deductAmount" label="实收租箱费总计" width="120"> </el-table-column>
        </el-table>
        <b>租箱费明细</b>
        <el-table :data="param.rentFeeDetail">
          <!-- <el-table-column type="index" label="序号" width="60"> </el-table-column> -->
          <el-table-column prop="orderNo" label="订单号"> </el-table-column>
          <el-table-column prop="carryCity" label="提箱城市"> </el-table-column>
          <el-table-column prop="ReturnCity" label="还箱城市"> </el-table-column>
          <el-table-column prop="createTime" label="下单日期" width="220"> </el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" width="120"> </el-table-column>
          <el-table-column prop="amount" label="订单金额(￥)" width="120"> </el-table-column>
          <el-table-column prop="containerQuantity" label="应收箱量" width="120"> </el-table-column>
          <el-table-column prop="actualPayAmount" label="应收租箱款(￥)" width="120"> </el-table-column>
        </el-table>
      </div>
      <div v-if="param.oprType == 'xiangTieFee'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>箱贴费
        </div>
        <b>箱贴费总计</b>
        <el-table :data="param.xiangTieFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应付箱量" width="120"> </el-table-column>
          <el-table-column prop="deductOverdueAmount" label="应扣超期费总计" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付箱贴费总计" width="120"> </el-table-column>
          <el-table-column prop="annulOverdueAmount" label="减免超期费总计" width="120"> </el-table-column>
          <el-table-column prop="paymentOverdueAmount" label="实扣超期费总计" width="120"> </el-table-column>
          <el-table-column prop="deductElseAmount" label="实扣其他费总计" width="120"> </el-table-column>
          <el-table-column prop="deductAmount" label="实付箱贴费总计"> </el-table-column>
        </el-table>
        <b>箱贴费明细</b>
        <el-table :data="param.xiangTieFeeDetail">
          <el-table-column type="index" label="序号" width="60"> </el-table-column>
          <el-table-column prop="containerNo" label="箱号"> </el-table-column>
          <el-table-column label="箱型" width="120">
            <template v-slot="scope">
              {{ param.containerTypeFilter[scope.row.containerType] }}
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="箱贴费($)" width="120"> </el-table-column>
          <el-table-column prop="overdueDays" label="超期天数" width="120"> </el-table-column>
          <el-table-column prop="overdueFee" label="超期费($)" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付箱贴费($)" width="120"> </el-table-column>
        </el-table>
      </div>
      <div v-if="param.oprType == 'pay'">
        <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>支付箱贴费
        </div>
        <b>箱贴费总计</b>
        <el-table :data="param.xiangTieFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应付箱量" width="120"> </el-table-column>
          <el-table-column prop="deductOverdueAmount" label="应扣超期费总计" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付箱贴费总计" width="120"> </el-table-column>
          <el-table-column prop="annulOverdueAmount" label="减免超期费总计" width="120"> </el-table-column>
          <el-table-column prop="paymentOverdueAmount" label="实扣超期费总计" width="120"> </el-table-column>
          <el-table-column prop="deductElseAmount" label="实扣其他费总计" width="120"> </el-table-column>
          <el-table-column prop="deductAmount" label="实付箱贴费总计"> </el-table-column>
        </el-table>
        <b>箱贴费明细</b>
        <el-table :data="param.xiangTieFeeDetail">
          <el-table-column type="index" label="序号" width="60"> </el-table-column>
          <el-table-column prop="containerNo" label="箱号"> </el-table-column>
          <el-table-column label="箱型" width="120">
            <template v-slot="scope">
              {{ param.containerTypeFilter[scope.row.containerType] }}
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="箱贴费($)" width="120"> </el-table-column>
          <el-table-column prop="overdueDays" label="超期天数" width="120"> </el-table-column>
          <el-table-column prop="overdueFee" label="超期费($)" width="120"> </el-table-column>
          <el-table-column prop="dealAmount" label="应付箱贴费($)" width="120"> </el-table-column>
        </el-table>
        <el-form ref="payFormRef" :model="param" :rules="payFormRules" label-width="200"
          style="margin: 50px 0 50px 100px;">
          <el-form-item label="优惠券">{{ 0 || '无' }}</el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="param.paymentMethod" style="width:220px" placeholder="选择">
              <el-option label="对公转账" value="5" />
              <el-option label="在线支付" value="10" />
            </el-select>
          </el-form-item>
          <el-form-item label="电子回执单" prop="payUrl">
            <imgUpload ref="payRef" :drag="false" style="width:100%"></imgUpload>
          </el-form-item>
          <el-form-item label="支付日期" prop="paymentDate">
            <el-date-picker v-model="param.paymentDate" type="date" placeholder="选择日期" />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="param.oprType == 'invoice'">
        <el-form label-width="200" style="margin: 50px 0 50px 100px;">
          <el-form-item label="申请发票类型：">{{ { 5: '对公转账', 10: '在线支付' }[invoice.invoiceType] }}</el-form-item>
          <el-form-item label="企业名称：">{{ invoice.businessName }}</el-form-item>
          <el-form-item label="统一社会信用代码：">{{ invoice.creditCode }}</el-form-item>
          <el-form-item label="发票：">
            <img-upload ref="invoiceRef" :needOcr="true" :drag="false" @ocrInvoiceNo="ocrInvoiceNo" />
          </el-form-item>
          <el-form-item label="发票号：" style="width: 400px;">
            <el-input v-model="invoice.invoiceNo" placeholder="请输入发票号" />
          </el-form-item>
        </el-form>
        <b>明细</b>
        <el-table :data="param.rentFeeDetail">
          <el-table-column prop="orderNo" label="订单号"> </el-table-column>
          <el-table-column prop="carryCity" label="提箱城市"> </el-table-column>
          <el-table-column prop="ReturnCity" label="还箱城市"> </el-table-column>
          <el-table-column prop="createTime" label="下单日期"> </el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" width="120"> </el-table-column>
          <el-table-column prop="amount" label="订单金额(￥)" width="120"> </el-table-column>
          <el-table-column prop="containerQuantity" label="应收箱量" width="120"> </el-table-column>
          <el-table-column prop="actualPayAmount" label="应收租箱款(￥)" width="120"> </el-table-column>
        </el-table>
        <b>合计</b>
        <el-table :data="param.rentFeeTotal">
          <el-table-column prop="needPayContainerNum" label="应收箱量"> </el-table-column>
          <el-table-column prop="dealAmount" label="应收租箱费总计"> </el-table-column>
          <el-table-column prop="deductAmount" label="实收租箱费总计" width="120"> </el-table-column>
        </el-table>
        <el-form label-width="200" style="margin: 30px 0 50px 100px;">
          <el-form-item label="结算币种：">
            <el-radio-group v-model="param.payCurrency">
              <el-radio value="USD" size="large">$</el-radio>
              <el-radio value="CNY" size="large">￥</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="本次执行汇率：">
            1美元 &nbsp;= &nbsp;
            <el-input-number v-model="param.rate" size="small" :controls="false" :min="1" :max="99.99" :precision="2"
              placeholder=" < 100" @blur="param.rate = param.rate ? param.rate : 1" style="width:100px" />
            &nbsp;元
          </el-form-item>
        </el-form>
      </div>

      <div style="text-align: center;margin-top: 20px;">
        <div class="dialog-footer">
          <el-button @click="param.dialogVisible = false">关闭</el-button>
          <el-button v-if="param.oprType == 'pay'" @click="handleSubmit('pay')" type="primary">确定</el-button>
          <el-button v-if="param.oprType == 'invoice'" @click="handleSubmit('invoice')" type="primary">提交</el-button>
        </div>
      </div>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import imgUpload from '@/components/upload/index.vue'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import { getInvoicePage, getInvoicesInfo } from '@/api/invoice/index'
// import pdfViewer from '@/components/pdf/viewer'
import pdfViewer from '@/components/pdf'
import { numMulti, numAdd } from '@/utils/compute'
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref } from 'vue';
import { View, List, FolderChecked, Ticket } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { rentUploadingInvoice, callbackUploadingInvoice, payBoxLabelInvoice } from '@/api/invoice'
import {DATA_directionFilter,DATA_invoiceDirections,DATA_invoiceStatuss,DATA_invoiceStatusFilter,DATA_stateColor} from '@/data/invoice.js'
const param = reactive({
  payCurrency: 'USD',
  rate: 1,
  // invoiceDirection: 1, //结算流向
  // invoiceStatus: 5, //发票状态
  closeStatus: '', //结算状态
  closeStatuss: [
    { value: '5', label: '未付'}, 
    { value: '10', label: '已付'},

    { value: '15', label: '未收'}, //  5(原始值) => 15（替代值）
    { value: '20', label: '已收'}, //  10(原始值) => 20（替代值）
  ],
  invoiceTypes: [  //5-增值税普通发票  10-增值税专用发票
    { value: 5, label: '增值税普通发票', },
    { value: 10, label: '增值税专用发票', },
  ],
  containerTypeFilter: { '5': '40HQ', '10': '40GP', '15': '20HQ', '20': '20GP' },

  radio: 0,
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出租中', 10: '仓库中', 15: '待发布' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  invoiceTypeFilter: { '5': '增值税普通发票', '10': '增值税专用发票' }, //5-增值税普通发票  10-增值税专用发票
  closeStatusFilter: { '5': '未付', '10': '已付' }, //5-未付  10-已付
  directionFilter: { '-1': '支出', '1': '收入' },

  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  invoiceTypeList: [{ value: 5, label: '增值税普通发票' }, { value: 10, label: '增值税专用发票' }],
  invoiceSources:[]
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'releaseRentId', colWidth: '220', title: 'releaseRentId', type: 'text', isCheck: true },   { value: 1, label: '收入', },
    { value: -1, label: '支出', },
    // { key: 'id', colWidth: '220', title: 'ID', type: 'text', isCheck: true },
    { key: 'invoiceNos', colWidth: '220', title: '发票号', type: 'text', isCheck: true },
    { key: 'invoiceOrder', key2: 'orderNo', colWidth: '220', title: '订单号', type: '/', isCheck: true },
    { key: 'invoiceDirection', colWidth: '120', title: '结算流向', type: 'filter', filter: param.directionFilter, isCheck: true },
    { key: 'invoiceTitle', colWidth: '100', title: '结算单位', type: 'text', isCheck: true },
    { key: 'creditCode', colWidth: '200', title: '纳税人识别号', type: 'text', isCheck: true },
    { key: 'invoiceType', colWidth: '200', title: '发票类型', type: 'filter', filter: param.invoiceTypeFilter, isCheck: true },
    { key: 'invoiceAmount', colWidth: '200', title: '开票金额', type: 'add', currency: 'currency', isCheck: true },
    { key: 'operate', colWidth: '100', title: '款项明细', type: 'operate', isCheck: true, buttons: [{ icon: 'List', command: 'activInfo', }] },
    { key: 'invoiceStatus', colWidth: '120', title: '发票状态', type: 'filter', filter: DATA_invoiceStatusFilter, cFilter: DATA_stateColor, isCheck: true },
    { key: 'createTime', colWidth: '200', title: '申请日期', type: 'date', isCheck: true },
    // { key: 'closeStatus', colWidth: '120', title: '结算状态', type: 'filter2', key2:"invoiceSource",roleType:'xd', isCheck: true },
    { key: 'closeStatus', colWidth: '120', title: '结算状态', type: 'filter2', key2:"invoiceDirection", isCheck: true },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        // {
        //   // name: '下单',
        //   icon: 'List',
        //   content: "款项明细",
        //   command: 'activInfo',
        // },
        // {
        //   icon: 'FolderChecked',
        //   content: "支付",
        //   command: 'activPay',
        //   isShow: (row: any) => {
        //     // return row.invoiceStatus == '15' && row.invoiceSource == 10;
        //     return row.invoiceStatus == '15';
        //   },
        // },
        {
          icon: 'View',
          content: "查看发票",
          command: 'showInvoice',
          isShow: (row: any) => {
            return row.invoiceStatus == '15';
          },
        },
        {
          icon: 'Ticket',
          content: "开发票",
          command: 'applyInvoice',
          isShow: (row: any) => {
            // return row.invoiceStatus < 15 && row.invoiceSource == 5;
            return row.invoiceStatus < 15;

          },
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

//初始化
function getTableData() {
  let statusInfo = param.closeStatus;
  switch (param.closeStatus) {
    case '5': //已收
      // param.closeStatus = '5' 
      statusInfo = '5'
      // param.invoiceSources = [10]
      break;
    case '10': //已收
      // param.closeStatus = '5'
      statusInfo = '10' 
      // param.invoiceSources = [10]
      break;
    case '15': //已收
      // param.closeStatus = '5' 
      statusInfo = '5' 
      // param.invoiceSources = [5]
      break;
    case '20': //未收
      // param.closeStatus = '10'
      statusInfo = '10' 
      // param.invoiceSources = [5]
      break;
    default:
      // param.invoiceSources = [5,10]
      break;

  }
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    invoiceDirection: param.invoiceDirection,
    orderNo: param.orderNo?.trim(),
    businessName: param.businessName?.trim(),
    invoiceNo: param.invoiceNo?.trim(),
    invoiceStatus: param.invoiceStatus,
    invoiceType: param.invoiceType,
    creditCode: param.creditCode?.trim(),
    closeStatus: statusInfo,
    invoiceSources:param.invoiceSources   //集装箱公司角色（此参数必传） =》 5-租箱 10-回调 15-购箱
  };
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0]
    data.endCreateDate = param.createDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getInvoicePage(data).then((res: any) => {
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.data.map((item: any) => {
      item.invoiceNos = item.invoiceNo
    });
    table.config.total = res.data.total;
  });
  table.config.loading = false;
}

function handleReset() {
  param.invoiceStatus = null
  param.invoiceDirection = null
  param.orderNo = null
  param.businessName = null
  param.invoiceNo = null
  param.invoiceStatus = null
  param.invoiceType = null
  param.creditCode = null
  param.closeStatus = null
  param.createDate = null
  getTableData()
}

// 发票识别
const ocrInvoiceNo = (val: any) => {
  invoice.value.invoiceNo = val.data.invoiceNo
}

//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  return tableRef.value.multipleSelection.map((item: any) => item.id)
})

//申请红冲
import { updateInvoiceStatus } from '@/api/invoice'
const applyRedInvoice = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const multipleSelection = checkAllItem
  if (multipleSelection.length < 1) return ElMessage.warning('请选择要操作的数据')
  ElMessageBox.confirm('您确定要申请红冲所选发票吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const invoiceIds = multipleSelection.map((item: any) => {
      const invoiceOrder = JSON.parse(item.invoiceOrder)
      const orderIds = invoiceOrder.map((item: any) => item.orderId)
      return {
        "id": item.id,
        "orderIds": orderIds
      }
    })
    updateInvoiceStatus({ "invoiceIds": JSON.stringify(invoiceIds) }).then((res: any) => {
      ElMessage.success('操作成功')
      getTableData()
    })
  }).catch(() => {
    ElMessage.info('取消操作')
  })
}

// 箱贴费/租箱款
const activInfo = (val: any) => {
  param.oprType = val.invoiceSource == 5 ? 'rentFee' : 'xiangTieFee' //invoiceSource:发票来源  5-租箱  10-回调
  param.dialogVisible = true
  getDetailAndTotal(val)
}

// 查看发票
const showInvoice = (row: any) => {
  // row.invoiceUrl = "[{\"url\": \"http://47.122.3.254:9000/default/20241114/ffec7468fa334bbab766ad4940f8380d.jpg\", \"name\": \"20241114/ffec7468fa334bbab766ad4940f8380d.jpg\", \"originalFileName\": \"t012254599220d8b0ae.jpg\"}]"
  if (!row.invoiceUrl) return ElMessage.error('chengzhi 未发现发票url')
  param.pdfUrl = JSON.parse(row.invoiceUrl) || []
  // param.pdfUrl = row.invoiceUrl //http://47.122.3.254:9000/default/template/发票文件.pdf
  param.oprType = 'img'
  param.dialogVisible = true
}

const invoice = ref({ payCurrency: 'USD' })
const activPay = (row: any) => {
  param.oprType = 'pay'
  param.dialogVisible = true
  invoice.value = row
  getDetailAndTotal(row)
}

//开发票
const applyInvoice = (row: any) => {
  param.oprType = 'invoice'
  param.dialogVisible = true
  invoice.value = row
  // console.log(invoice.value)
  getDetailAndTotal(row)
}

// 提交/确定支付 
const invoiceRef = ref()
const payRef = ref()
const { proxy } = getCurrentInstance();
const handleSubmit = (oprType: string) => {
  if (oprType == 'pay') {  // 支付箱贴费
    param.payUrl = payRef.value.resultList || []
    proxy.$refs.payFormRef.validate(valid => {
      if (!valid) return
      const imgList = param.payUrl
      // 支付箱贴费
      const data = {
        "id": invoice.value.id,
        "paymentMethod": param.paymentMethod,//5-对公转账  10-在线支付
        "payDate": param.paymentDate,
        "payUrl": JSON.stringify(imgList)
        // "payUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]"
      }
      payBoxLabelInvoice(data).then((res: any) => {
        getTableData()
        param.dialogVisible = false
        ElMessage({ message: '支付成功', type: 'success' })
      })
    })
  }
  if (oprType == 'invoice') { // 开发票 
    const resultList = invoiceRef.value.resultList || []
    if (resultList.length == 0) {
      return ElMessage({ message: '请上传发票', type: 'warning' })
    }
    if (!invoice.value.invoiceNo) {
      return ElMessage({ message: '请输入发票号', type: 'warning' })
    }
    const dealAmount = param.rentFeeTotal[0].dealAmount // 应收/付 租箱费总计
    const deductAmount = param.rentFeeTotal[0].deductAmount //实收/付 租箱费总计
    const payContainerNum = param.rentFeeTotal[0].needPayContainerNum//应收/付 租箱量总计
    // param.rentFeeDetail.map((item: any) => {
    //   item.containerQuantity = item.containerQuantity
    // })
    const data = {
      "id": invoice.value.id,
      "payCurrency": param.payCurrency,
      "rate": param.rate,
      "invoiceNo": invoice.value.invoiceNo,
      "invoiceUrl": JSON.stringify(resultList),
      "dealAmount": dealAmount,
      "deductAmount": deductAmount,
      "payContainerNum": payContainerNum,
      "containerNoDetail": JSON.stringify(param.rentFeeDetail),
      // "containerNoDetail": "[{\"amount\": \"20000.0\", \"orderNo\": \"ZLOID2024062041957343\", \"carryCity\": \"郑州/中国\", \"ReturnCity\": \"上海/中国\", \"createTime\": \"2024-08-27 16:00:00\", \"boxQuantity\": \"2\", \"containerQuantity\": \"1\", \"actualPayAmount\": \"10000.0\"},{\"amount\": \"30000.0\", \"orderNo\": \"ZLOID2024062042695102\", \"carryCity\": \"郑州/中国\", \"ReturnCity\": \"上海/中国\", \"createTime\": \"2024-08-27 16:00:00\", \"boxQuantity\": \"2\", \"containerQuantity\": \"1\", \"actualPayAmount\": \"15000.0\"}]",
    }
    rentUploadingInvoice(data).then((res: any) => {
      getTableData()
      param.dialogVisible = false
    })
  }

}

function getDetailAndTotal(val: any) {
  getInvoicesInfo(val.id).then((res: any) => {
    param.invoiceInfo = res.data
    if (param.oprType == 'xiangTieFee') {
      param.xiangTieFeeDetail = JSON.parse(res.data.containerNoDetail)
      param.xiangTieFeeTotal = [{ needPayContainerNum: param.xiangTieFeeDetail.length, deductOverdueAmount: param.invoiceInfo.deductOverdueAmount, dealAmount: param.invoiceInfo.dealAmount, annulOverdueAmount: param.invoiceInfo.annulOverdueAmount, paymentOverdueAmount: param.invoiceInfo.paymentOverdueAmount, deductAmount: param.invoiceInfo.deductAmount, deductElseAmount: param.invoiceInfo.deductElseAmount }]
    }
    if (['rentFee', 'invoice'].includes(param.oprType)) {
      param.rentFeeDetail = JSON.parse(res.data.containerNoDetail)
      param.rentFeeTotal = [{ needPayContainerNum: param.invoiceInfo.payContainerNum, dealAmount: param.invoiceInfo.dealAmount, deductAmount: param.invoiceInfo.deductAmount }]
    }
    if (param.oprType == 'pay') {
      param.xiangTieFeeDetail = JSON.parse(res.data.containerNoDetail)
      param.xiangTieFeeTotal = [{ needPayContainerNum: param.xiangTieFeeDetail.length, deductOverdueAmount: param.invoiceInfo.deductOverdueAmount, dealAmount: param.invoiceInfo.dealAmount, annulOverdueAmount: param.invoiceInfo.annulOverdueAmount, paymentOverdueAmount: param.invoiceInfo.paymentOverdueAmount, deductAmount: param.invoiceInfo.deductAmount, deductElseAmount: param.invoiceInfo.deductElseAmount }]
    }
  })
}

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

onActivated(() => {
  getTableData()
})

//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  if (value > new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('支付日期 必须小于等于今天'))
  }
  return callback()
}
const payFormRules = {
  paymentMethod: [
    { required: true, message: '支付方式不能为空', trigger: 'change' },
  ],
  payUrl: [
    { required: true, message: '发票抬头不能为空', trigger: 'change' },
  ],
  paymentDate: [
    { required: true, message: '支付日期不能为空', trigger: 'blur' },
    { validator: validatePlanPackingDate, trigger: 'blur' }
  ],
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getInvoicePage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

</script>

<style lang="scss" scoped></style>